package com.kaxiu.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kaxiu.config.redis.RedisService;
import com.kaxiu.config.shiro.jwt.JwtConfig;
import com.kaxiu.config.shiro.jwt.JwtToken;
import com.kaxiu.persistent.entity.Account;
import com.kaxiu.persistent.entity.BasicUser;
import com.kaxiu.persistent.entity.SysRoleUser;
import com.kaxiu.persistent.mapper.AccountMapper;
import com.kaxiu.persistent.mapper.BasicUserMapper;
import com.kaxiu.persistent.mapper.SysRoleUserMapper;
import com.kaxiu.service.IBasicUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * <p>
 * 用户信息 服务实现类
 * </p>
 *
 * @author ly
 * @since 2019-08-04
 */
@Service
public class BasicUserServiceImpl extends ServiceImpl<BasicUserMapper, BasicUser> implements IBasicUserService {

    @Autowired
    private BasicUserMapper mapper;

    @Autowired
    private SysRoleUserMapper roleUserMapper;

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private RedisService redisService;


    @Override
    @Transactional
    public BasicUser saveBasicUser(BasicUser userInfo, Integer roleId) {
        /**
         * 1. 没有该用户信息
         * 2. 已经有了该用户，没有手机号
         * 3. 有用户，有手机
         * 4. 有手机，没有用户
         */
        BasicUser existUser = mapper.selectOne(Wrappers.<BasicUser>lambdaQuery().eq(BasicUser::getOpenId, userInfo.getOpenId()));
        if(existUser == null){
            int i = mapper.insert(userInfo);
                // 新增用户-角色
            if(i > 0){
                SysRoleUser roleUser = new SysRoleUser();
                roleUser.setSysRoleId(String.valueOf(roleId));
                roleUser.setSysUserId(String.valueOf(userInfo.getId()));
                roleUserMapper.insert(roleUser);
                //            新增account
                Account account = new Account();
                account.setUserId(String.valueOf(userInfo.getId()));
                accountMapper.insert(account);
            }
            return userInfo;
        }else{
            return existUser;
        }
    }

    @Override
    public int bindMobile(String mobile) {
        BasicUser user = redisService.getWxUser();
        user.setMobile(mobile);
        return mapper.updateById(user);
    }

    @Override
    public BasicUser findByLogin(String currentLoginMobile) {
        return mapper.selectOne(Wrappers.<BasicUser>lambdaQuery().eq(BasicUser::getMobile, currentLoginMobile));
    }

    @Override
    public BasicUser findByOpenId(String openId) {
        return mapper.selectOne(Wrappers.<BasicUser>lambdaQuery().eq(BasicUser::getOpenId, openId));
    }

}
